<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\UserModel;
use App\Models\VipGoodsModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VipController extends ApiController
{
    /**
     * 获取列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getList(Request $request): JsonResponse
    {
        $sid = $request->input('sid');
        $pagination = VipGoodsModel::where('sid', $sid)->paginate(10);
        $items = json_decode(json_encode($pagination->items()), true);
        $userUuids = array_column($items, 'uuid');
        $users = UserModel::whereIn('uuid', $userUuids)->get(['uuid', 'mobile', 'username']);
        return $this->success([
            'total'  => $pagination->total(),
            'page'   => $pagination->currentPage(),
            'limit'  => $pagination->perPage(),
            'pages'  => $pagination->lastPage(),
            'list'   => $users
        ]);
    }

    /**
     * 保存
     * @param Request $request
     * @return JsonResponse
     */
    public function doSave(Request $request): JsonResponse
    {
        $username = $request->input('username');
        $user = UserModel::where('username', $username)->select('uuid', 'id')->first();
        if ($user) {
            if (!VipGoodsModel::where('uuid', $user->uuid)->where('sid', $request->input('sid'))->first())
                VipGoodsModel::create([
                    'uid'  => $user->id,
                    'uuid' => $user->uuid,
                    'sid'  => $request->input('sid'),
                ]);
        }
        return $this->success();
    }
}
